<template>
	<div class="group-post-edit clear">
		<div class="post-edit-l fl">
			<el-button class="post-back-btn" type="text" @click="goback()">
				<i class="el-icon-arrow-left"></i>返回</el-button>
			<template>
				<div class="input-post-tit">
					<span>{{ ruleForm.post_title || "请输入标题" }}</span>
					<!-- <input v-model.trim="search_title" type="text" placeholder="搜索标题"> -->
					<i :class="[currentRow == null ? '' : 'el-icon-delete']" @click="del_post_title(currentRow)"></i>
				</div>
				<el-table class="post-title-table" :show-header="false" highlight-current-row @current-change="handleCurrentChange"
				 style="width: 100%" ref="post_tit_table" :data="
                        post_title_data.filter(
                            data =>
                                !search_title ||
                                data.title
                                    .toLowerCase()
                                    .includes(search_title.toLowerCase())
                        )
                    ">
					<el-table-column show-overflow-tooltip>
						<template slot-scope="scope" class="t_b_color">{{
                            scope.row.title
                        }}</template>
					</el-table-column>
				</el-table>
				<el-pagination v-if="total_number > page_size" @current-change="change_page" :page-size="page_size" :current-page="page_index"
				 layout="prev, pager, next" :total="total_number">
				</el-pagination>
			</template>
		</div>
		<div class="post-edit-m fl">
			<template>
				<uploader class="uploader-example" ref="uploader" :options="uploadOptions" :file-status-text="statusText"
				 @file-added="fileAdded" @file-removed="fileRemoved" @files-submitted="filesSubmitted" @file-progress="fileProgress"
				 @file-success="fileSuccess" @file-error="fileFail">
					<uploader-unsupport></uploader-unsupport>
					<uploader-btn :directory="false" :single="true" v-if="resource_data.length < 3 && !disabledUplader">上传附件</uploader-btn>
					<el-button v-else class="disabled-uploader" disabled>上传附件</el-button>
				</uploader>
			</template>
			<div :class="
                    progressing
                        ? 'uploader-progress-active'
                        : 'uploader-progress'
                ">
				<img v-if="uploadingFile.file_type" :src="fileNameData[uploadingFile.file_type].path" :alt="fileNameData[uploadingFile.file_type].alt" />
				<div class="uploader-file-info">
					<p class="file-name" :title="uploadingFile.file_name">
						{{ uploadingFile.file_name }}
					</p>
					<div class="progress-row">
						<template v-if="percentage < 100">
							<el-progress :percentage="percentage" color="#33BBBB"></el-progress>
							<span class="cancelUpload" @click="fileCancel"></span>
						</template>
						<template v-else>
							<span class="finsh">上传完成</span>
							<i class="el-icon-delete" @click="fileCancel"></i>
						</template>
					</div>
				</div>
			</div>
			<ul>
				<li class="entry-file-list clear" v-for="(item, index) in resource_data" :key="index">
					<img :src="fileNameData[item.file_type].path" :alt="fileNameData[item.file_type].alt" />
					<span class="fileName">{{ item.name }}</span>
					<div>
						<!-- <span v-text="renderSize(item.filesize)"></span> -->
						<span>{{ item.create_time }}</span>
					</div>
					<i class="el-icon-delete" @click="del_resource(item.id)"></i>
				</li>
			</ul>
		</div>
		<div class="post-edit-r fl">
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" :inline-message="true">
				<el-form-item class="post-title-item" prop="post_title">
					<el-input v-model.trim="ruleForm.post_title" maxlength="20" placeholder="请输入标题"></el-input>
				</el-form-item>
				<el-form-item class="post-content-item">
					<tinymce id="d1" :plugins="plugins" :other_options="options" :toolbar1="toolbar1" :toolbar2="toolbar2" v-model="ruleForm.post_content"
					 @editorInit="editorInit"></tinymce>
					<div class="post-content-count">
						<i>{{ tinymceNum }}/</i><i class="gery">10000</i>
					</div>
				</el-form-item>
				<el-button class="post-btns-item" size="medium" type="text" @click="submitForm('ruleForm')">发帖子</el-button>
			</el-form>
		</div>
	</div>
</template>
<script>
	import axios from "../../../tools/axios";
	import tinymce from "vue-tinymce-editor";
	import CN from "./../../../assets/tinymce_languages/zh_CN.js";

	export default {
		data() {
			return {
				user_login_id: this.$store.getters.userInfo.id,
				group_id: this.$route.query.id,
				post_id: this.$route.query.p_id,
				editFlag: this.$route.query.p_id ? true : false,
				page_index: 1,
				page_size: 12,
				total_number: 0,
				post_title_data: [],
				search_title: "",
				currentRow: null, //左侧点击选择的标题数据
				resource_id_string: "",
				//中间部分：上传资源
				fileNameData: [{
						alt: "其他",
						path: require("../../../../public/images/format/resourceicon8.png")
					},
					{
						alt: "文档",
						path: require("../../../../public/images/format/resourceicon1.png")
					},
					{
						alt: "日志",
						path: require("../../../../public/images/format/resourceicon2.png")
					},
					{
						alt: "图片",
						path: require("../../../../public/images/format/resourceicon3.png")
					},
					{
						alt: "压缩文件",
						path: require("../../../../public/images/format/resourceicon4.png")
					},
					{
						alt: "音乐",
						path: require("../../../../public/images/format/resourceicon5.png")
					},
					{
						alt: "视频",
						path: require("../../../../public/images/format/resourceicon6.png")
					},
					{
						alt: "应用程序",
						path: require("../../../../public/images/format/resourceicon7.png")
					},
					{
						alt: "其他",
						path: require("../../../../public/images/format/resourceicon8.png")
					}
				],
				resource_data: [],
				statusText: {
					success: "上传成功",
					error: "上传出错",
					uploading: "正在上传...",
					paused: "暂停",
					waiting: "等待上传"
				},
				uploadOptions: {
					target: this.BASE_URL + "/api/resource/res_upload",
					testChunks: false,
					// singleFile:true,
					headers: {
						Authorization: `Bearer ` + this.$g.access_token
					}
				},
				uploadingFile: {}, //上传中文件
				progressing: false, // 是否正在上传附件
				disabledUplader: false, // 上传附件过程中，不可以在上传
				percentage: 0, // 附件上传进度
				//右侧富文本
				p_t_index: 0,
				ruleForm: {
					post_title: "",
					post_content: ""
				},
				tinymceNum: 0, // 编辑器文本内容初始长度
				rules: {
					post_title: [{
							required: true,
							message: "您还没请输入标题"
						},
						{
							min: 3,
							max: 20,
							message: "长度在 3 到 20 个字符"
						}
					]
					// post_content: [
					//   { required: true, message: "请填写内容" },
					//   { min: 3, max: 10000, message: "长度在 3 到 10000 个字符" }
					// ]
				},
				plugins: ["paste", "fullscreen", "link", "image"],
				toolbar1: " ",
				toolbar2: 'table |insertfile undo redo | formatselect  | fontsizeselect | forecolor backcolor | fontselect bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | removeformat', // 编辑器工具栏
				options: {
					images_upload_handler: this.images_upload_handler,
					language_url: CN,
					images_upload_url: this.BASE_URL + "/api/resource/res_upload_permanent",
					paste_data_images: true, // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
					paste_convert_word_fake_lists: false, // 插入word文档需要该属性
					paste_webkit_styles: "all",
					paste_merge_formats: true,
					nonbreaking_force_tab: false,
					paste_auto_cleanup_on_paste: false,
					font_formats: `
                        微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;
                        宋体='宋体',Helvetica,Arial,sans-serif;
						仿宋='仿宋',Helvetica,Arial,sans-serif;
                        楷体='楷体',Helvetica,Arial,sans-serif;
                        黑体='黑体',Helvetica,Arial,sans-serif;
                        幼圆='幼圆',Helvetica,Arial,sans-serif;
                        隶书='隶书',Helvetica,Arial,sans-serif;
                        华文新魏='华文新魏',Helvetica,Arial,sans-serif;
                        苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;
                        Arial='Arial',Helvetica,Arial,sans-serif;
                        Verdana=verdana,geneva;
                        Webdings=webdings
                `,
				},
				fileNumber: 0
			};
		},
		created() {
			this.getPostsList();
		},
		watch: {
			/**
			 * 监听富文本的内容长度，判断是否超出规定内容
			 */
			"ruleForm.post_content"(newVal, oldVal) {
				setTimeout(() => {
					let body = document
						.getElementById("d1_ifr")
						.contentWindow.document.getElementsByTagName("body")[0]
						.textContent;
					let newLen = body.replace(/\s/g, "").length;
					let oldLen = this.tinymceNum;

					// 判断输入的内容文本长度是否超过 10000
					if (newLen > 10000) {
						this.$message.warning("内容最大长度不可以超过 10000 个字");
						this.tinymceNum = oldLen;
						this.ruleForm.post_content = oldVal;
					} else {
						this.tinymceNum = newLen;
					}
				}, 300);
			}
		},
		methods: {
			//编辑器初始化
			editorInit() {
				//修改输入框内文字与边界的宽
				var test = document
					.getElementById("d1_ifr")
					.contentWindow.document.getElementById("tinymce");
				test.style.margin = "60px 25px 8px";
			},
			getPostsList() {
				let _params = {
					pid: 0,
					group_id: this.group_id,
					page_index: this.page_index,
					page_size: this.page_size,
					order: "create_time", //create_time,clicks
					drection: "DESC", //正序DESC，反序不填
					is_tree: 0, //是否获取下级（1是，0不是,不发不是）
					id: null, //讨论id
					create_id: this.user_login_id
				};
				let success = res => {
					this.post_title_data = res.data.data;
					this.page_index = parseInt(res.data.page_index);
					this.total_number = parseInt(res.data.data_sum);
					this.find_post_index(res.data.data); //跳到此页面进行编辑的时候，默认选中对应的帖子
				};
				this.$ajax.get("api/group/subject_group_chat", {
					params: _params,
					func: {
						success: success
					}
				});
			},
			//对比帖子id值,判断哪个标题被选中
			find_post_index(arr) {
				arr.find((value, index, arr) => {
					if (this.post_id == value.id)
						// table选中row事件
						this.$refs.post_tit_table.setCurrentRow(
							this.post_title_data[index]
						);
				});
			},
			// table选中时触发事件
			handleCurrentChange(val) {
				this.resource_data = [];
				this.currentRow = val;
				if (val != undefined) {
					if (val.resource != undefined) {
						this.resource_data = val.resource;
						//拼字符串，号隔开
						this.resource_id_string = arrChangeString(
							val.resource,
							"id"
						);
					}
					this.ruleForm.post_title = val.title;
					this.ruleForm.post_content = val.content;
				}
			},
			//删帖子
			del_post_title(_del_row) {
				this.$confirm("确定删除吗?", "提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning",
						customClass: "confirm-them"
					})
					.then(() => {
						let del_params = {
							id: _del_row.id,
							title: _del_row.title,
							content: _del_row.content,
							resource_id: _del_row.resource_id,
							status: 0
						};
						this.change_post_data(del_params, "put");
						this.ruleForm.post_title = "";
						this.ruleForm.post_content = "";
						this.goback();
					})
					.catch(() => {});
			},
			// 新建帖子/编辑帖子公用函数
			change_post_data(_params, _method) {
				let success = res => {
					this.$message.success(res.msg);
					this.goback();
					this.getPostsList();
				};
				let fail = res => {
					this.$message.error(res.msg);
				};
				if (_method == "post") {
					this.$ajax.post("api/group/subject_group_chat", _params, {
						func: {
							success: success,
							fail: fail
						}
					});
				} else if (_method == "put") {
					this.$ajax.put("api/group/subject_group_chat", _params, {
						func: {
							success: success,
							fail: fail
						}
					});
				}
			},
			// 引入common.js里的公用函数，格式化文件大小
			renderSize(value) {
				return renderSize(value);
			},
			//添加附件
			fileAdded(file) {
				// console.log(file)
				// 上传第一个是，数组为空
				if (this.resource_data.length > 2) {
					this.$message.error("附件数量不能超过3个");
					file.ignored = true;
					return;
				}
				if (file.size > 100 * 1024 * 1024) {
					this.$message.error("附件大小不能超过100M");
					file.ignored = true;
					return false;
				}
				this.percentage = 0;
				this.progressing = true;
				this.disabledUplader = true;
			},
			//移除附件
			fileRemoved(file) {
				this.progressing = false;
				this.disabledUplader = false;
			},
			//所选择的附件添加到上传队列后触发
			filesSubmitted(files, fileList) {
				let ext = files[0].name
					.split(".")
					.pop()
					.toLocaleLowerCase();
				if (ext === "mpg") {
					this.$message.error("不允许上传的此类格式的文件");
					this.$refs.uploader.uploader.removeFile(files[0]);
					return false;
				}
			},
			//附件上传中
			fileProgress() {
				this.percentage = parseInt(
					this.$refs.uploader.uploader.progress() * 100
				);
			},
			fileCancel() {
				this.$refs.uploader.uploader.cancel();
				this.disabledUplader = false;
			},
			//上传附件成功
			fileSuccess(rootFile, file, message, chunk) {
				// this.progressing = false;
				this.disabledUplader = false;
				let mess = eval("(" + message + ")");
				mess = handleResponseData(mess);
				this.uploadFile(mess);
			},
			//提交附件去后台
			uploadFile(mess) {
				this.uploadingFile = mess.data; //正在上传文件的信息
				this.resource_id_string = "";
				const fileName = mess.data.file_name.substring(0,mess.data.file_name.length - mess.data.post_fix.length-1);
				var params = {
					file_path: mess.data.file_path,
					file_type: mess.data.file_type,
					file_name: fileName,
					post_fix: mess.data.post_fix,
					group_id: this.group_id
				};
				let success = res => {
					this.$message.success(res.msg);
					if (this.resource_id_string === "") {
						this.resource_id_string += res.data;
					} else {
						this.resource_id_string += "," + res.data;
					}
				};
				this.$ajax.post("/api/group/bind_chat_resource", params, {
					func: {
						success: success
					}
				});
			},
			// 上传附件失败
			fileFail(rootFile, file, message, chunk) {
				this.progressing = false;
				let mess = eval("(" + message + ")");
				if (parseInt(mess.error) === 401 && this.uploadRetryTimes > 0) {
					let callbcak = data => {
						this.uploadRetryTimes--;
						this.$refs.uploader.uploader.retry(file);
					};
					this.get_access_token(callbcak);
				} else {
					this.disabledUplader = false;
					this.$message.error(mess.msg);
				}
			},
			//删除帖子附件
			del_resource(_id) {
				let success = res => {
					this.getPostsList();
					this.$message.success(res.msg);
				};
				this.$ajax({
					url: "api/resource/resource",
					method: "delete",
					params: {
						id: _id,
						del_type: 1
					},
					func: {
						success: success
					}
				});
			},
			//发帖子时验证
			submitForm(formName) {
				//判断附件是否还在上传
				if (this.$refs.uploader.uploader.isUploading() == true) {
					this.$message.error("附件还没上传完成");
					return false;
				}
				//判断内容
				this.$refs[formName].validate(valid => {
					if (valid) {
						let _resource_id = this.resource_id_string.replace(
							/(^\,*)|(\,*$)/g,
							""
						); //去除资源id组成的字符串首尾的逗号
						//新增帖子
						let params_add = {
							title: this.ruleForm.post_title,
							content: this.ruleForm.post_content,
							pid: 0,
							resource_id: _resource_id,
							group_id: this.group_id
						};
						//编辑帖子
						let params_edit = {
							id: this.post_id,
							title: this.ruleForm.post_title,
							content: this.ruleForm.post_content,
							resource_id: _resource_id,
							status: 1,
							group_id: this.group_id
						};
						if (this.editFlag) {
							this.change_post_data(params_edit, "put");
						} else {
							this.change_post_data(params_add, "post");
						}
					} else {
						console.log("error submit!!");
						return false;
					}
				});
			},

			// 图片上传三个参数，图片数据，成功时的回调函数，失败时的回调函数
			images_upload_handler(blobInfo, success, failure) {
				if (blobInfo.blob().type.indexOf("image/") === -1) {
					failure("只允许上传图片格式的文件");
				} else if (blobInfo.blob().size > 10240000) {
					failure("图片大小不能超过10M");
				} else {
					let formData = new FormData();
					formData.append("file", blobInfo.blob(), blobInfo.filename());
					let succ = data => {
						success(this.BASE_URL + data.data.data.file_path);
					};
					let fail = data => {
						failure(data.data.data.message);
					};
					const instance = axios.create({
						headers: {
							Authorization: `Bearer ${this.$g.access_token}`,
							DecisionPlatform: ` ${this.$g.access_token}`,
							token: sessionStorage.getItem("token")
						},
						withCredentials: true
					});
					instance
						.post("api/resource/res_upload_permanent", formData)
						.then(succ)
						.catch(fail);
				}
			},
			// 分页
			change_page(val) {
				this.page_index = val;
				this.getPostsList();
			},
			goback() {
				this.$router.back(-1);
			}
		},
		components: {
			tinymce
		}
	};
</script>

<style lang="scss">
	.main {
		// padding: 0;
	}

	.hideDrop {
		opacity: 0;
		visibility: hidden;
	}

	.group-post-edit {
		.post-edit-m {
			.uploader {
				padding: 33px;
				border-bottom: 1px solid #ebeef5;
			}

			.uploader-btn {
				padding: 8px 13px;
				font-size: 14px;
				color: #fff;
				border: none;
				border-radius: 4px;
				background: #409eff;
			}

			.uploader-btn:hover {
				color: #fff;
				background: rgba(52, 142, 252, 0.8);
			}

			.uploader-progress {
				display: none;
			}

			.uploader-progress-active {
				display: flex;
				justify-content: flex-start;
				padding: 14px 0;
				font-size: 14px;

				img {
					object-fit: none;
				}

				.uploader-file-info {
					padding-left: 20px;

					.file-name {
						display: inline-block;
						width: 220px;
						white-space: nowrap;
						text-overflow: ellipsis;
						overflow: hidden;
						line-height: 20px;
					}

					.progress-row {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.el-progress,
						.finsh {
							display: inline;
							margin-right: 52px;
						}

						.cancelUpload {
							color: #409eff;
							cursor: pointer;
						}

						.finsh {
							font-size: 12px;
							line-height: 20px;
							color: #888888;
						}

						.el-icon-delete {
							font-size: 20px;
							color: #f56c6c;
							// padding: 10px 10px 10px 28px;
							cursor: pointer;
						}
					}
				}
			}
		}
	}
</style>
